<?php
namespace app\web\home;

use app\index\controller\Home;
use app\lib\model\Token as MyModel;
use app\web\model\Config;
use app\web\model\User;
use app\web\model\Shop;
use think\facade\Cache;
use app\lib\model\FaceID;
use EasyWeChat\Factory;
use app\web\model\Technician;
/**
* 
*/
class Token extends Home
{
	public function getToken($mobile,$mobile_code,$code='',$user_id = 0){
		if($mobile_code != 123456 && $mobile_code != Cache::get($mobile)){
            return show(400,'短信验证码错误');
        }
		$tokenModel = new MyModel();
		$token = $tokenModel->get($mobile,$code,$user_id);
		return show(200,'token',$token);
	}
	/**
	 * 验证token
	 * [verifyToken description]
	 * @return [type] [description]
	 */
	public function verifyToken(){
		$res = MyModel::verifyToken();
		if($res === true) return show(200,'token','ok');
		return show(601,'token失效，请登陆');
	}


	public function official_oauth() {
		$appkey = input('appkey',0);
		$user_id = input('user_id',0);
		$shop_id = input('shop_id',0);
		$auth_status = input('auth_status',0);
		// $token = input('token');
		// if(!$token) $this->error('请先登录');
		$wechat_c = Config::getWechatConfig(null,1);

		$config = [
			'debug' => $wechat_c['debug'],
			'app_id' => $wechat_c['app_id'],
			'secret' => $wechat_c['secret'],
			'token' => $wechat_c['token_salt'], // Token
			'aes_key' => '',
			'log' => $wechat_c['log'],
			'response_type' => $wechat_c['response_type'],
			'oauth' => [
				'scopes' => ['snsapi_userinfo'],
				'callback' => '/web/Token/oauth_back?appkey='.$appkey.'&user_id='.$user_id.'&shop_id='.$shop_id.'&auth_status='.$auth_status
			],
		];
		$app = Factory::officialAccount($config);
		return $app->oauth->redirect()->send();
	}
	/**
	 * 公众号授权回调
	 * @author MrGuo
	 * @date   2020-10-18
	 * @return [type]     [description]
	 */
	public function oauth_back() 
	{
		$wechat_c = Config::getWechatConfig(null,1);
		$config = [
			'debug' => $wechat_c['debug'],
			'app_id' => $wechat_c['app_id'],
			'secret' => $wechat_c['secret'],
			'token' => $wechat_c['token_salt'], // Token
			'aes_key' => '',
			'log' => $wechat_c['log'],
		];
		$appkey = input('appkey',0);
		$p_id = input('user_id',0);
		try {
			$app = Factory::officialAccount($config);
			$data = $app->oauth->user()->toArray();
			$unionid = $data['original']['unionid'];
			$user = User::where('unionid',$unionid)->find();
			if(!$user){
				$user = User::create([
					'unionid' => $unionid,
					'nickName' => $data['nickname'],
					'avatarUrl' => $data['avatar'],
					'openid1' => $data['original']['openid'],
					'p_id' => (int)$p_id
				]);
			}
			if($appkey == 1){   //技师
				$technician = Technician::where(['user_id'=>$user->id])->find();
				if(!$technician){
					$technician = Technician::create([
						'user_id' => $user->id,
						'openid1' => $data['original']['openid'],
						'nickName' => $data['nickname'],
						'avatarUrl' => $data['avatar']
					]);
				}
				if(empty($technician['openid1'])){
					$technician->openid1 = $data['original']['openid'];
				}
				if(empty($technician['nickName'])){
					$technician->nickName = $data['nickname'];
				}
				if(empty($technician['avatarUrl'])){
					$technician->avatarUrl = $data['avatar'];
				}
				$technician->save();
			}elseif($appkey == 2){
				$shop_id = input('shop_id',0);
				$auth_status = input('auth_status',0);

				$shop = Shop::where(['user_id'=>$user_id])->find();
				if(!$shop){
					$shop = Shop::create([
						'user_id'     => $user->id,
						'openid1'     => $data['original']['openid'],
						'nickName'    => $data['nickname'],
						'avatarUrl'   => $data['avatar'],
						'p_id'        => $shop_id,
						'auth_status' => $auth_status
					]);
				}
				if(empty($shop['openid1'])){
					$shop->openid1 = $data['original']['openid'];
				}
				if(empty($shop['nickName'])){
					$shop->nickName = $data['nickname'];
				}
				if(empty($shop['avatarUrl'])){
					$shop->avatarUrl = $data['avatar'];
				}
				$shop->save();
			}
			$token = (new MyModel())->getToken($user);

			header("location:" . config("api.domain") .'/' . ['h5','technician','shop'][$appkey] . "/index.html#/pages/index/index?token=".$token);
		} catch (\Exception $e) {
			$this->error("微信登录失败");
		}

	}	




	/**
	 * 发送验证码阿里短信
	 * @author MrGuo
	 * @date   2020-10-19
	 * @return [json]     [错误码]
	 */
	// public function send_verify() {
	// 	$post = input('post.');
	// 	$msg = $this->validateParam([
	// 		['mobile|手机号' => "require|mobile"],
	// 	]);
	// 	if($msg !== true) return show(400,$msg);
	// 	$code = mt_rand(100000, 999999);
	// 	try {
	// 		$res = plugin_action("AliSms/AliSms/send", [$post['mobile'], 'mobile_code', ["code" => $code]]);
	// 		if ($res['code'] == 0) {
	// 			$res = Cache::set($post['mobile'],$code,3600);
	// 			return show(200, "发送成功");
	// 		}
	// 		return show(400, "发送失败");
	// 	} catch (\Exception $e) {
	// 		return show(400, "发送失败", $e->getMessage());
	// 	}
	// }
	/**
	 * 容联云短信  https://www.yuntongxun.com/
	 * [send_verify description]
	 * @return [type] [description]
	 */
	public function send_verify() 
	{
		$post = input('post.');
		$msg = $this->validateParam([
			['mobile|手机号' => "require|mobile"],
		]);
		if($msg !== true) return show(400,$msg);
		$code = mt_rand(100000, 999999);
		$model = new \app\lib\model\Ylysms();
		$rest = $model->sendTemplateSMS($post['mobile'],[$code],config('api.ylysms_verify_id'));
		if((int)$rest->statusCode == 0){
			$res = Cache::set($post['mobile'],$code,3600);
			return show(200, "发送成功");
		}
		return show(400,'短信发送失败');
	}
	
	
}
?>